package org.btik.light.mobile.ui.factory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.IdRes;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import org.btik.light.mobile.common.handler.serial.OnClickSerialSender;
import org.btik.light.mobile.common.handler.serial.SerialController;

import java.io.IOException;
import java.util.HashSet;

/**
 * @author lustre
 * @since 2023/4/7 21:00
 */
public abstract class SerialControllerPanel extends Activity {
    protected UsbSerialPort usbSerialPort;
    protected final HashSet<SerialController> serialControllerSet = new HashSet<>();

    protected <T extends View> T bind(@IdRes int id, OnClickSerialSender onClickListener) {
        T viewById = findViewById(id);
        serialControllerSet.add(onClickListener);
        onClickListener.bindUsbSerialPort(usbSerialPort);
        viewById.setOnClickListener(onClickListener);
        return viewById;
    }

    @SuppressLint("ClickableViewAccessibility")
    protected <T extends View> T bind(@IdRes int id, View.OnTouchListener onTouchListener) {
        T viewById = findViewById(id);
        if (onTouchListener instanceof SerialController) {
            ((SerialController) onTouchListener).bindUsbSerialPort(usbSerialPort);
        }
        viewById.setOnTouchListener(onTouchListener);
        return viewById;
    }

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    protected Switch bind(@IdRes int id, CompoundButton.OnCheckedChangeListener onCheckedChangeListener) {
        Switch aSwitch = findViewById(id);
        if (onCheckedChangeListener instanceof SerialController) {
            ((SerialController) onCheckedChangeListener).bindUsbSerialPort(usbSerialPort);
        }
        aSwitch.setOnCheckedChangeListener(onCheckedChangeListener);
        return aSwitch;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            usbSerialPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (SerialController serialController : serialControllerSet) {
            serialController.disAttach();
        }
        serialControllerSet.clear();
    }
}
